import {gainCoupon, getCouonList} from "../../api/coupon";
import Util from "../../utils/util";
import {getBannerData} from "../../api/api";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    lists: [],
    et_show: true,

    btnActive: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 当前页面参数
    const that = this;

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
        loadend: false,
        loading: false,
        list: [],
        page: 1,
      });

      that.getLists()
      wx.hideLoading()
    }).catch(errmsg => {
      wx.hideLoading()
    })
    // this.onLoadTabbar();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  getLists() {
    const that = this
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      wx.stopPullDownRefresh()
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});

    let filter = that.data.filter || {}
    filter['page_num'] = that.data.page;
    getCouonList(filter).then(res => {

      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = app.SplitArray(list, lists);

      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        page: that.data.page + 1,
        et_show: lists.length > 0
      });

      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      wx.stopPullDownRefresh()
      app.Tips({title: errmsg})
    })
  },

  gainCoupon(e) {
    const that = this,
      key = e.currentTarget.dataset.key || 0;

    let couponList = that.data.lists || [];

    if (!this.data.btnActive)
      return false;
    this.setData({
      btnActive: false
    })

    wx.showLoading({title: "正在领取..."})
    gainCoupon(couponList[key].id).then(res => {
      couponList[key].mapping = res.data || null;
      that.setData({
        lists: couponList,
        btnActive: true
      })
      Util.Tips({title: "领取成功"})
    }).catch(errmsg => {
      that.setData({
        btnActive: false
      })
      Util.Tips({title: errmsg, hideMask: true})
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})